#!/bin/bash

# 获取ipam service的ClusterIP
ipam_svc_ip=$(kubectl --kubeconfig=/etc/kubernetes/{{ cluster_name }}/admin.conf get svc -n {{ scud.namespace }} scud-ipam-server -o json |python -c "import json,sys;data=json.load(sys.stdin);print data['spec']['clusterIP']")

if [[ "$ipam_svc_ip"x == ""x ]] ; then
	echo "get ipam service cluster-ip failed, exit"
	exit 1
fi
echo "" >> {{ cluster_name }}-openssl-for-ipam.conf
echo "IP.1 = $ipam_svc_ip" >> {{ cluster_name }}-openssl-for-ipam.conf

# 生成服务端证书
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr -subj "/CN=scud-ipam-server/C=CN/ST=ZheJiang/L=HangZhou/O=scud" -config {{ cluster_name }}-openssl-for-ipam.conf
openssl x509 -req -in server.csr -CA /etc/kubernetes/{{ cluster_name }}/pki/ca.crt -CAkey /etc/kubernetes/{{ cluster_name }}/pki/ca.key -CAcreateserial -out server.crt -days 36500 -extensions v3_req -extfile {{ cluster_name }}-openssl-for-ipam.conf
openssl x509 -in server.crt -noout -text

# 生成客户端证书
openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr -subj "/CN=scud-ipam-client/C=CN/ST=ZheJiang/L=HangZhou/O=scud"
openssl x509 -req -in client.csr -CA /etc/kubernetes/{{ cluster_name }}/pki/ca.crt -CAkey /etc/kubernetes/{{ cluster_name }}/pki/ca.key -CAcreateserial -out client.crt -days 36500 -extensions v3_req
openssl x509 -in client.crt -noout -text

kubectl -n {{ scud.namespace }} --kubeconfig=/etc/kubernetes/{{ cluster_name }}/admin.conf delete secret scud-ipam-server-tls ; \
kubectl -n {{ scud.namespace }} --kubeconfig=/etc/kubernetes/{{ cluster_name }}/admin.conf create secret generic scud-ipam-server-tls --from-file=server.key --from-file=server.crt --from-file=/etc/kubernetes/{{ cluster_name }}/pki/ca.crt

kubectl -n {{ scud.namespace }} --kubeconfig=/etc/kubernetes/{{ cluster_name }}/admin.conf delete secret scud-cni-tls ; \
kubectl -n {{ scud.namespace }} --kubeconfig=/etc/kubernetes/{{ cluster_name }}/admin.conf create secret generic scud-cni-tls --from-file=client.key --from-file=client.crt --from-file=/etc/kubernetes/{{ cluster_name }}/pki/ca.crt
